﻿namespace LiteBlog.Common.Entities
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;

    public class ArchiveMonth : IEqualityComparer<ArchiveMonth>
    {
        private static readonly string NameFormat = "MMM yyyy";
        private static readonly string IdFormat = "MMMyyyy";
        private static readonly int StartYear = 1990;

        public ArchiveMonth() : this(1)
        {
        }

        public ArchiveMonth(int month, int year)
        {
            Id = GetArchiveId(month, year);
            Month = month;
            Year = year;
            Count = 1;
        }

        public ArchiveMonth(int archiveId)
        {
            Id = archiveId;
            Month = (archiveId - 1) % 12 + 1;
            Year = (archiveId - 1) / 12 + StartYear;
            Count = 1;
        }

        public int Id { get; set; }
        public int Month { get; set; }
        public int Year { get; set; }
        public int Count { get; set; }
        
        public string Name
        {
            get
            {
                DateTime dt = new DateTime(Year, Month, 1);
                return dt.ToString(NameFormat, System.Globalization.CultureInfo.InvariantCulture);
            }
        }

        public string MonthName
        {
            get
            {
                DateTime dt = new DateTime(Year, Month, 1);
                return dt.ToString("MMMM", null);
            }
        }

        public string Url
        {
            get
            {
                return string.Format("~/{0}/{1:00}", Year, Month);
            }
        }

        public static int GetArchiveId(int month, int year)
        {
            if (year < StartYear)
                return 0;
            return month + ((year - StartYear) * 12);
        }

        public static string GetMonthId(DateTime date)
        {
            return date.ToString(IdFormat);
        }

        public static DateTime GetTimeForMonthId(string monthId)
        {
            return DateTime.ParseExact(monthId, IdFormat, null, DateTimeStyles.None);
        }

        public bool Equals(ArchiveMonth x, ArchiveMonth y)
        {
            return (x.Month == y.Month) && (x.Year == y.Year);
        }

        public int GetHashCode(ArchiveMonth obj)
        {
            return (new { Month = obj.Month, Year = obj.Year }).GetHashCode();
        }

        public static IEqualityComparer<ArchiveMonth> Comparer
        {
            get
            {
                return new ArchiveMonth();
            }
        }
    }
}